using System;
using System.Linq;
using JNPF.Utils;
using System.Threading.Tasks;
using JNPF.Data;
using JNPF.Data.Util;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using JNPF.Basics.Models;
using System.Data.Common;
using System.Text;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace JNPF.Basics.Logic
{
    public class PartnerService : DataFactory, PartnerIService
    {
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<PartnerEntity> GetInfo(int id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<PartnerEntity>(m => m.Id == id && m.DeleteMark == 0);
            }
        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<PartnerEntity> GetInfoByMobilePhone(string mobilePhone)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<PartnerEntity>(m => m.MobilePhone == mobilePhone && m.DeleteMark == 0);
            }
        }



        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<PartnerEntity>> GetPageList(PartnerListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<PartnerEntity>();
                var queryParam = input.queryJson.ToObject();
                //查询手机号
                if (!string.IsNullOrEmpty(input.mobilePhone))
                {
                    queryWhere = queryWhere.And(m => m.MobilePhone.Contains(input.mobilePhone));
                }
                //查询姓名
                if (!string.IsNullOrEmpty(input.realName))
                {
                    queryWhere = queryWhere.And(m => m.RealName.Contains(input.realName));
                }

                //查询姓名
                if (!string.IsNullOrEmpty(input.userId))
                {
                    queryWhere = queryWhere.And(m => m.UserId.Contains(input.userId));
                }
                //查询姓名
                if (input.enabledMark.HasValue)
                {
                    queryWhere = queryWhere.And(m => m.EnabledMark == input.enabledMark);
                }
                queryWhere = queryWhere.And(m => m.DeleteMark == 0);
                return await db.GetIQueryable<PartnerEntity>().Where(queryWhere).GetPageResultAsync(input);
            }
        }



        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<PartnerUpOutput>> GetPageListBySql(PartnerListQueryInput input)
        {

            input.sidx = "F_CreatorTime";

            UserInfo userInfo = UserProvider.Instance.Get();
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	                        partner.*,
	                        buser.F_RealName   ParentRealName 
                        FROM
	                        jiushi_partner partner
	                        LEFT JOIN base_user buser ON partner.F_UserId = buser.F_Id
	                        where 1=1 and partner.F_DeleteMark = 0 ");

                //查询手机号
                if (!string.IsNullOrEmpty(input.mobilePhone))
                {

                    dbSql.Append(" AND partner.F_MobilePhone like  @mobilePhone");
                    parameters.Add(DataHelper.CreateParameter("@mobilePhone", "%" + input.mobilePhone + "%"));
                }
                //查询手机号
                if (!string.IsNullOrEmpty(input.realName))
                {
                    dbSql.Append(" AND partner.F_RealName like  @realName");
                    parameters.Add(DataHelper.CreateParameter("@realName", "%" + input.realName + "%"));
                }
                if (input.enabledMark.HasValue)
                {
                    dbSql.Append(" AND partner.F_EnabledMark =  @enabledMark");
                    parameters.Add(DataHelper.CreateParameter("@enabledMark", input.enabledMark));

                }
                //查询手机号
                if (!string.IsNullOrEmpty(input.parentRealName))
                {
                    dbSql.Append(" AND buser.F_RealName like  @parentRealName");
                    parameters.Add(DataHelper.CreateParameter("@parentRealName", "%" + input.parentRealName + "%"));
                }
                if (!input.isAdmin)
                {
                    //自己只能看到自己的
                    dbSql.Append(" and partner.F_USERID =  @userId");
                    parameters.Add(DataHelper.CreateParameter("@userId", userInfo.UserId));
                }
                return await PageHelper.GetPageResultAsync<PartnerUpOutput>(db, input, dbSql.ToString(), parameters.ToArray());
            }
        }



        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(PartnerEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }




        /// <summary>
        /// 审核合伙人
        /// </summary>
        /// <param name="partnerEntity"></param>
        /// <param name="entity"></param>
        /// <param name="userRelationList"></param>
        /// <param name="userextendEntity"></param>
        /// <param name="newneedsEntity"></param>
        /// <returns></returns>
        public async Task Create(PartnerEntity partnerEntity, UserEntity entity, List<UserRelationEntity> userRelationList, UserextendEntity userextendEntity, NewneedsEntity newneedsEntity)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();


                await db.UpdateAsync(partnerEntity);

                await db.InsertAsync(entity);

                await db.InsertAsync(userextendEntity);

                await db.InsertAsync(userRelationList);

                await db.InsertAsync(newneedsEntity);

                await db.CommitTransactionAsync();
            }
        }




        /// <summary>
        /// 审核合伙人添加
        /// </summary>
        /// <param name="partnerEntity"></param>
        /// <param name="entity"></param>
        /// <param name="userRelationList"></param>
        /// <param name="userextendEntity"></param>
        /// <param name="newneedsEntity"></param>
        /// <returns></returns>
        public async Task CreateInsert(PartnerEntity baseEntity, UserEntity entity, List<UserRelationEntity> userRelationList, UserextendEntity userextendEntity, NewneedsEntity newneedsEntity)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();

                await db.UpdateAsync(baseEntity);

                await db.UpdateAsync(entity);


                await db.InsertAsync(userRelationList);

                if (userextendEntity.Id > 0)
                {
                    await db.UpdateAsync(userextendEntity);
                }
                else
                {
                    await db.InsertAsync(userextendEntity);
                }

                await db.InsertAsync(newneedsEntity);




                await db.CommitTransactionAsync();
            }
        }











        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(PartnerEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(PartnerEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.DeleteAsync(entity);
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<List<PartnerEntity>> GetList(PartnerListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<PartnerEntity>();
                //查询手机号
                if (!string.IsNullOrEmpty(input.mobilePhone))
                {
                    queryWhere = queryWhere.And(m => m.MobilePhone.Contains(input.mobilePhone));
                }
                //查询姓名
                if (!string.IsNullOrEmpty(input.realName))
                {
                    queryWhere = queryWhere.And(m => m.RealName.Contains(input.realName));
                }
                queryWhere = queryWhere.And(m => m.DeleteMark == 0);
                return await db.GetIQueryable<PartnerEntity>().Where(queryWhere).ToListAsync();
            }
        }


    }
}